package cn.virens.common.components.timer;

import cn.hutool.core.thread.ThreadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

public class ExecutorManager {
    private static final Logger logger = LoggerFactory.getLogger(ExecutorManager.class);

    private int startDelay = 0;
    private boolean isStoped = false;

    private final ExecutorService executor;

    private ExecutorManager(int threadSize) {
        this.executor = ThreadUtil.newExecutor(threadSize);
    }

    public static ExecutorManager of(int threadSize) {
        return new ExecutorManager(threadSize);
    }

    public void execute(ExecutorRunnable runnable, long timeout, String name) {
        this.executor.execute(() -> {
            // 延时启动
            ThreadUtil.sleep(startDelay, TimeUnit.SECONDS);

            logger.debug("This {} thread is runing...", name);

            long run = 0;
            while (isStoped == false) {
                long s = System.currentTimeMillis();
                logger.debug("This {} thread run {} times.", name, run++);

                try {
                    runnable.run();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    long e = System.currentTimeMillis();
                    logger.debug("This {} thread runs for {} milliseconds.", name, (e - s));
                }

                // 线程休息指定时间
                ThreadUtil.sleep(timeout, TimeUnit.SECONDS);
            }

            logger.debug("This {} thread is stoped...", name);
        });
    }

    public boolean isStoped() {
        return isStoped;
    }

    public void setStoped(boolean isStoped) {
        this.isStoped = isStoped;
    }

    public int getStartDelay() {
        return startDelay;
    }

    public void setStartDelay(int startDelay) {
        this.startDelay = startDelay;
    }

    public void shutdown() throws Exception {
        this.executor.shutdown();
    }
}
